<%@page import="javax.mail.internet.MimeUtility"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String fileName = "我爱你_爱してる_I love you_.txt";//文件名
	String fileContent = "";//文件内容
	fileContent = "001 汉语：我爱你 wǒ ai nǐ \n\r "
			+ "002 英语：I love you \n\r 003 法语：je t'aime "
			+ "004 德语：ich liebe dich   \n\r 005 希腊语：σε αγαπώ se agapo  \n\r"
			+ "033 日本语：爱してる aishiteru \n\r 034 韩国语（朝鲜语）：사랑해（요）sa lang hae（ yo）";

	String type = request.getParameter("type");//Content-Disposition类型

	if (type != null && !"".equals(type)) {

		response.setContentType("application/x-download");//设置为下载application/x-download
		String cd = "attachment;filename=" + fileName;//Content-Disposition

		if ("0".equals(type)) {
		    cd = "attachment;filename=" + fileName;
		}else if ("1".equals(type)) {
			cd = "attachment;filename=\"" + fileName + "\"";
		} else if ("2".equals(type)) {//UTF-8
			fileName = URLEncoder.encode(fileName, "UTF-8");
			fileName = fileName.replaceAll("[+]", "%20");
			cd = "attachment;filename=\"" + fileName + "\"";
		} else if ("3".equals(type)) {//UTF-8 RFC2231的定义
			fileName = URLEncoder.encode(fileName, "UTF-8");
			fileName = fileName.replaceAll("[+]", "%20");
			cd = "attachment;filename*=\"UTF-8''" + fileName + "\"";
		} else if ("4".equals(type)) {//Base64 编码
			fileName = MimeUtility.encodeText(fileName, "UTF8", "B");
			cd = "attachment;filename=\"" + fileName + "\"";
		} else if ("5".equals(type)) {//ISO8859-1
			fileName = new String(fileName.getBytes("UTF-8"),
					"ISO8859-1");
			cd = "attachment;filename=\"" + fileName + "\"";
		}

		fileContent += "\n\r======================================\n\r";
		fileContent += "Content-Disposition:" + cd;

		response.addHeader("Content-Disposition", cd);

		OutputStream outputStream = response.getOutputStream();
		outputStream.write(fileContent.getBytes());
		outputStream.flush();
		outputStream.close();
		outputStream = null;

		out.clear();//不加这两句会报错~ getOutputStream() has already been called for this response
		out = pageContext.pushBody();
		return;
	}
%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件下载文件名正确</title>
</head>
<body>

	文件下载:
	<br> 文件名:<%=fileName%><br> 文件内容:<%=fileContent%><br>

	<br>
	<a href="?type=0">type=0 filename=filename</a>
	<br>
	<a href="?type=1">type=1 filename="filename"</a>
	<br>
	<a href="?type=2">type=2 filename="filename" (encode UTF-8)</a>
	<br>
	<a href="?type=3">type=3 filename*="UTF-8''filename" (RFC2231)</a>
	<br>
	<a href="?type=4">type=4 filename="filename" (Base64 UTF-8)</a>
	<br>
	<a href="?type=5">type=5 filename="filename" (UTF-8 to ISO8859-1)</a>
	<br>

</body>
</html>